package com.mall.order.mq;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;

import java.nio.charset.StandardCharsets;

/**
 * @author Darren
 * @date 2022-09-13 15:15
 * Description：
 */
public class OrderResultListener implements RocketMQListener, RocketMQPushConsumerLifecycleListener {
    /**
     * 监听消息
     *
     * @param o
     */
    @Override
    public void onMessage(Object o) {
        System.out.println("监听消息 ---> " + o);
    }

    /**
     * 消息监听
     *
     * @param defaultMQPushConsumer
     */
    @Override
    public void prepareStart(DefaultMQPushConsumer consumer) {
        consumer.registerMessageListener((MessageListenerConcurrently) (list, context) -> {
            try {
                for (MessageExt msg : list) {
                    String result = new String(msg.getBody(), StandardCharsets.UTF_8);
                    System.out.println("result ---> " + result);
                }
            } catch (Exception e) {
                // 消费失败，回滚
                e.printStackTrace();
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });
    }
}
